import React, { useState } from 'react';
import { Card, Button, Select, DatePicker, Space, message, Row, Col, Divider, Typography } from 'antd';
import { DownloadOutlined, FileExcelOutlined, FileTextOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useCities } from '../hooks/useWeatherQueries';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Title, Text } = Typography;

interface ExportDataPanelProps {
  onClose?: () => void;
}

const ExportDataPanel: React.FC<ExportDataPanelProps> = ({ onClose }) => {
  const [loading, setLoading] = useState(false);
  const [exportType, setExportType] = useState<'weather' | 'statistics' | 'cities'>('weather');
  const [format, setFormat] = useState<'excel' | 'csv'>('excel');
  const [selectedCityId, setSelectedCityId] = useState<string | undefined>();
  const [dateRange, setDateRange] = useState<[any, any] | null>(null);
  const [statisticType, setStatisticType] = useState<string | undefined>();

  const { data: cities = [] } = useCities();

  const downloadFile = (blob: Blob, filename: string) => {
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
  };

  const handleExport = async () => {
    if (exportType === 'statistics' && !selectedCityId) {
      message.error('导出统计数据时必须选择城市');
      return;
    }

    setLoading(true);
    try {
      let url = '/api/export/';
      const params: any = {};

      // 构建URL和参数
      switch (exportType) {
        case 'weather':
          url += `weather/${format}`;
          if (selectedCityId) params.cityId = selectedCityId;
          if (dateRange) {
            params.startDate = dateRange[0]?.format('YYYY-MM-DD');
            params.endDate = dateRange[1]?.format('YYYY-MM-DD');
          }
          break;
        case 'statistics':
          url += 'statistics/excel'; // 统计数据目前只支持Excel
          params.cityId = selectedCityId;
          if (statisticType) params.statisticType = statisticType;
          if (dateRange) {
            params.startDate = dateRange[0]?.format('YYYY-MM-DD');
            params.endDate = dateRange[1]?.format('YYYY-MM-DD');
          }
          break;
        case 'cities':
          url += 'cities/excel';
          break;
      }

      const response = await axios.get(url, {
        params,
        responseType: 'blob',
      });

      // 从响应头获取文件名
      const contentDisposition = response.headers['content-disposition'];
      let filename = `export_${Date.now()}.${format === 'excel' ? 'xlsx' : 'csv'}`;
      
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
        if (filenameMatch?.[1]) {
          filename = filenameMatch[1].replace(/['"]/g, '');
        }
      }

      downloadFile(response.data, filename);
      message.success('导出成功！');
    } catch (error: any) {
      console.error('导出失败:', error);
      message.error(`导出失败: ${error.response?.data?.message || error.message}`);
    } finally {
      setLoading(false);
    }
  };

  const getExportTypeText = () => {
    switch (exportType) {
      case 'weather': return '天气数据';
      case 'statistics': return '统计数据';
      case 'cities': return '城市数据';
      default: return '';
    }
  };

  return (
    <Card title="数据导出" style={{ maxWidth: 600 }}>
      <Space direction="vertical" style={{ width: '100%' }} size="large">
        {/* 导出类型选择 */}
        <div>
          <Title level={5}>导出类型</Title>
          <Select
            value={exportType}
            onChange={setExportType}
            style={{ width: '100%' }}
            size="large"
          >
            <Option value="weather">
              <Space>
                <FileExcelOutlined />
                天气数据
              </Space>
            </Option>
            <Option value="statistics">
              <Space>
                <FileExcelOutlined />
                统计数据
              </Space>
            </Option>
            <Option value="cities">
              <Space>
                <FileExcelOutlined />
                城市数据
              </Space>
            </Option>
          </Select>
        </div>

        {/* 文件格式选择 */}
        {exportType !== 'cities' && exportType !== 'statistics' && (
          <div>
            <Title level={5}>文件格式</Title>
            <Select
              value={format}
              onChange={setFormat}
              style={{ width: '100%' }}
              size="large"
            >
              <Option value="excel">
                <Space>
                  <FileExcelOutlined style={{ color: '#1DB954' }} />
                  Excel (.xlsx)
                </Space>
              </Option>
              <Option value="csv">
                <Space>
                  <FileTextOutlined style={{ color: '#FF6B6B' }} />
                  CSV (.csv)
                </Space>
              </Option>
            </Select>
          </div>
        )}

        {/* 筛选条件 */}
        {(exportType === 'weather' || exportType === 'statistics') && (
          <>
            <Divider>筛选条件</Divider>
            
            <Row gutter={16}>
              <Col span={24}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>选择城市:</Text>
                  <Select
                    placeholder={exportType === 'statistics' ? '请选择城市（必填）' : '全部城市'}
                    style={{ width: '100%', marginTop: 8 }}
                    value={selectedCityId}
                    onChange={setSelectedCityId}
                    allowClear={exportType !== 'statistics'}
                    size="large"
                  >
                    {cities.map((city: any) => (
                      <Option key={city.id} value={city.id}>
                        {city.name} ({city.country})
                      </Option>
                    ))}
                  </Select>
                </div>
              </Col>
              
              <Col span={24}>
                <div style={{ marginBottom: 16 }}>
                  <Text strong>时间范围:</Text>
                  <RangePicker
                    value={dateRange}
                    onChange={setDateRange}
                    format="YYYY-MM-DD"
                    placeholder={['开始日期', '结束日期']}
                    style={{ width: '100%', marginTop: 8 }}
                    size="large"
                  />
                </div>
              </Col>

              {exportType === 'statistics' && (
                <Col span={24}>
                  <div style={{ marginBottom: 16 }}>
                    <Text strong>统计类型:</Text>
                    <Select
                      placeholder="全部统计类型"
                      style={{ width: '100%', marginTop: 8 }}
                      value={statisticType}
                      onChange={setStatisticType}
                      allowClear
                      size="large"
                    >
                      <Option value="Daily">每日统计</Option>
                      <Option value="Weekly">每周统计</Option>
                      <Option value="Monthly">每月统计</Option>
                    </Select>
                  </div>
                </Col>
              )}
            </Row>
          </>
        )}

        {/* 导出按钮 */}
        <div style={{ textAlign: 'center', marginTop: 24 }}>
          <Space size="middle">
            <Button
              type="primary"
              icon={<DownloadOutlined />}
              size="large"
              loading={loading}
              onClick={handleExport}
              style={{ minWidth: 120 }}
            >
              导出{getExportTypeText()}
            </Button>
            {onClose && (
              <Button size="large" onClick={onClose}>
                取消
              </Button>
            )}
          </Space>
        </div>

        {/* 说明信息 */}
        <div style={{ background: '#f0f2f5', padding: 16, borderRadius: 6, marginTop: 16 }}>
          <Title level={5} style={{ marginBottom: 8 }}>导出说明：</Title>
          <ul style={{ marginBottom: 0, paddingLeft: 20 }}>
            <li>Excel格式支持数据筛选和样式，推荐用于数据分析</li>
            <li>CSV格式体积小，适合程序处理和导入其他系统</li>
            <li>大量数据导出可能需要较长时间，请耐心等待</li>
            <li>统计数据导出需要选择具体城市</li>
          </ul>
        </div>
      </Space>
    </Card>
  );
};

export default ExportDataPanel;